package work.jame.dynamic.aop;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StringUtils;
import work.jame.dynamic.annonation.DataSource;
import work.jame.dynamic.core.DynamicContextHolder;

import java.lang.reflect.Method;

/**
 * @author : Jame
 * @date : 2023-11-25 14:11
 **/
public class DynamicDataSourceAnnotationInterceptor implements MethodInterceptor {

    private final String defaultDataSourceKey;

    public DynamicDataSourceAnnotationInterceptor(String defaultDataSourceKey) {
        this.defaultDataSourceKey = defaultDataSourceKey;
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        try {
            Method method = invocation.getMethod();
            DataSource dataSource = method.getAnnotation(DataSource.class);
            String dynamicDataSourceKey;
            if (dataSource != null) {
                dynamicDataSourceKey = dataSource.value();
            } else {
                DataSource cDataSource = method.getDeclaringClass().getAnnotation(DataSource.class);
                if (cDataSource == null) {
                    dynamicDataSourceKey = defaultDataSourceKey;
                } else {
                    dynamicDataSourceKey = cDataSource.value();
                }
            }
            if (!StringUtils.hasText(dynamicDataSourceKey)) {
                dynamicDataSourceKey = defaultDataSourceKey;
            }
            DynamicContextHolder.push(dynamicDataSourceKey);
            return invocation.proceed();
        } finally {
            DynamicContextHolder.poll();
        }
    }
}
